//
//  Passerelles.m
//  Truffle
//
//  Created by Ismaila Kredity on 08/02/10.
//  Copyright 2010 kredity. All rights reserved.
//

#import "ServiceListViewController.h"
#import "Service.h"
#import "ServiceDetailsViewController.h"
#import "RestConnection.h"
#import "DatasTruffle.h"
#import "Gateway.h"
#import "ServiceListRestDelegate.h"
#import "FavoriteGatewayViewController.h"

@implementation ServiceListViewController

@synthesize gatewayList;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	self.title = @"Services";
	
	[activityIndicator setHidesWhenStopped:TRUE];
	[activityIndicator startAnimating];
	
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
											  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
											  target:self action:@selector(editFavouriteGateways:)];
	
	UIBarButtonItem *reloadButton = [[UIBarButtonItem alloc] 
									 initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh   
									 target:self 
									 action:@selector(refreshAction)];
	
	[self.navigationItem setLeftBarButtonItem:reloadButton];
	self.navigationItem.leftBarButtonItem.enabled = YES;
	
	/*** VERIFIER CONNECTIVITE ***/
	if(![DatasTruffle isConnected]) {
		NSLog(@">>[ServiceListView] Appli not connected, cannot us function in services");
	} else {
	
		/*** INITIALISATIONS ***/
		gatewayToServicesMap = [[NSMutableDictionary alloc] init];
		restToGatewayMap = [[NSMutableDictionary alloc] init];
		sectionToGatewayNameMap = [[NSMutableDictionary alloc] init];
	
		/*** RECUPERATION DES PASSERELLES ***/
		gatewayList = [DatasTruffle getGateways];

		/*** DEMANDER LISTE SERVICES POUR CHAQUE PASSERELLE ***/
		for(int cpt=0;cpt<[gatewayList count];cpt++) { // TODO : put cpt back to 0 at start	
		
			// New version
			restConnection = [RestConnection new];
			restConnection.baseURLString = [NSString stringWithFormat:@"%@/iphone/listservices", [[gatewayList objectAtIndex:cpt] ip]];
			ServiceListRestDelegate *sld = [[ServiceListRestDelegate alloc] init];
			sld.myPass = self;
			sld.restConnection = restConnection;
			restConnection.delegate = sld;
		
			// AJOUT DE L'URL A LA TABLE DE HASHAGE AVEC LE NOM DE LA PASSERELLE //
			[restToGatewayMap setObject:[[gatewayList objectAtIndex:cpt] name] forKey:restConnection.baseURLString];
			[sectionToGatewayNameMap setObject:[[gatewayList objectAtIndex:cpt] name] forKey:[NSString stringWithFormat:@"%d", cpt]];
		
			NSString *urlString = @"";
			[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
		
		}
	}	
}

/*Refresh de la page */
- (void)refreshAction {

	[super viewDidLoad];
	self.title = @"Services";
	
	[activityIndicator startAnimating];
	
	/*** VERIFIER CONNECTIVITE ***/
	if(![DatasTruffle isConnected]) {
		NSLog(@">>[ServiceListView] Appli not connected, cannot us function in services");
	} else {
		
		[gatewayToServicesMap release];
		[restToGatewayMap release];
		[sectionToGatewayNameMap release];
		
		/*** INITIALISATIONS ***/
		gatewayToServicesMap = [[NSMutableDictionary alloc] init];
		restToGatewayMap = [[NSMutableDictionary alloc] init];
		sectionToGatewayNameMap = [[NSMutableDictionary alloc] init];
		
		/*** RECUPERATION DES PASSERELLES ***/
		gatewayList = [DatasTruffle getGateways];
		
		/*** DEMANDER LISTE SERVICES POUR CHAQUE PASSERELLE ***/
		for(int cpt=0;cpt<[gatewayList count];cpt++) { // TODO : put cpt back to 0 at start	
			
			// New version
			[restConnection release];
			restConnection = [RestConnection new];
			restConnection.baseURLString = [NSString stringWithFormat:@"%@/iphone/listservices", [[gatewayList objectAtIndex:cpt] ip]];
			ServiceListRestDelegate *sld = [[ServiceListRestDelegate alloc] init];
			sld.myPass = self;
			sld.restConnection = restConnection;
			restConnection.delegate = sld;
			
			// AJOUT DE L'URL A LA TABLE DE HASHAGE AVEC LE NOM DE LA PASSERELLE //
			[restToGatewayMap setObject:[[gatewayList objectAtIndex:cpt] name] forKey:restConnection.baseURLString];
			[sectionToGatewayNameMap setObject:[[gatewayList objectAtIndex:cpt] name] forKey:[NSString stringWithFormat:@"%d", cpt]];
			
			NSString *urlString = @"";
			[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
			
		}
	}
	
}	

- (void) editFavouriteGateways:(id)sender {
	
	FavoriteGatewayViewController *favGates = [[FavoriteGatewayViewController alloc] initWithNibName:@"FavoriteGatewayViewController" bundle:nil];
	
	[self.navigationController pushViewController:favGates animated:YES];
	
}

- (void)receiveNewServiceTable:(NSMutableArray *)servTable restURL:(NSString*)restconn {
	[gatewayToServicesMap setObject:servTable forKey:[restToGatewayMap objectForKey:restconn]];

	[activityIndicator stopAnimating];
	
	[tableView reloadData];
	
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{	
	return [NSString stringWithFormat:@"%@ (%d)", [[gatewayList objectAtIndex:section] name], [[gatewayToServicesMap objectForKey:[[gatewayList objectAtIndex:section] name]] count]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	[tableView reloadData];
	
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellAccessoryDisclosureIndicator;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tblView {
	
	return [gatewayList count];
}


- (NSInteger)tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
	
	return [[gatewayToServicesMap objectForKey:[[gatewayList objectAtIndex:section] name]] count];
}


- (UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"Cell";
	UILabel * typeRef;
	
	UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	}
	
	int nbviews = [[cell subviews] count];
	UIFont *displayFont = [UIFont boldSystemFontOfSize:12];
	
	[cell addSubview:[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]];
	typeRef = [[cell subviews] objectAtIndex:nbviews];
	
	int ro = indexPath.row;
	int sec = indexPath.section;
	
	NSString * cellText = [[[gatewayToServicesMap objectForKey:[[gatewayList objectAtIndex:sec] name]] objectAtIndex:ro] servicename];
	
	cell.textLabel.text = cellText;
	cell.imageView.image = nil;
	cell.accessoryView = nil;
	
	typeRef.font = displayFont;
	return cell;
}
 
- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	serviceDetails = [[ServiceDetailsViewController alloc] initWithNibName:@"ServicesDetails" bundle:nil];
	
	int ro = indexPath.row;
	int sec = indexPath.section;
	
	
	serviceDetails.assignedService = [[gatewayToServicesMap objectForKey:[[gatewayList objectAtIndex:sec] name]] objectAtIndex:ro];
	serviceDetails.myPass = self;
	serviceDetails.gatewayIndexSection = sec;
	serviceDetails.gatewayIndexRow = ro;
	
	[self.navigationController pushViewController:serviceDetails animated:YES];
	
	[tableView reloadData];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}


@end
